package com.woniuxy.auth.controller;

import cn.hutool.json.JSONUtil;
import com.hc.entity.Perm;
import com.hc.entity.User;
import com.hc.utils.JwtUtil;
import com.hc.utils.ResponseEntity;
import com.woniuxy.auth.service.PermService;
import com.woniuxy.auth.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LoginController
 * @Description 用户登录：roleId-1 用户；roleId-2 商家；roleId-3 管理员
 * @Author shanshan
 * @Date 2022/10/24 9:10
 * @Version 1.0
 **/
@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;


//    @Autowired
//    private RedisTemplate<String, Object> redisTemplate;


    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private JwtUtil jwtUtil = new JwtUtil();


    //测试
    @PostMapping("/author")
    public ResponseEntity<Boolean> author(@RequestBody User user){
        //根据用户信息，查询用户的是否具有操作权限
        //service:redis
        //dao
        return new ResponseEntity("200", "success", true);
    }

    @PostMapping("/login")
    public ResponseEntity login(@RequestBody User user){
        //调用service和dao方法，判断用户名密码是否匹配
        User userlogin = userService.login(user);
        if (userlogin == null) {
            return ResponseEntity.LOGINFAIL;
        }
        //登录成功,生成token,存入响应头
        String token = jwtUtil.createJWT(userlogin.getId(), userlogin.getAccount(),userlogin.getRole().getId());
        log.debug("token:{}",token);
        //存在redis不用放header
//        response.setHeader("Access-Control-Expose-Headers", "token");
//        response.setHeader("token", token);
        //token存入redis,用于判断过期和续期
        //user存入redis,用于查询权限列表
//        redisTemplate.opsForValue().set("token"+userlogin.getId(), token, 30, TimeUnit.MINUTES);
//        redisTemplate.opsForValue().set("user"+userlogin.getId(), userlogin,30,TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("token"+userlogin.getId(), token, 30, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("user"+userlogin.getId(), JSONUtil.toJsonStr(userlogin),30,TimeUnit.MINUTES);
        return new ResponseEntity("200"+userlogin.getRole().getId(),"loginsuccess",token);
    }
}